package com.hanthink.system.service.impl.repair;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

import com.github.pagehelper.util.StringUtil;
import com.hanthink.common.enums.HiddenDangerType;
import com.hanthink.common.enums.PushType;
import com.hanthink.system.mapper.user.UserMapper;
import com.hanthink.system.service.impl.WeChatMessageServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hanthink.common.constant.BusinessConstants;
import com.hanthink.common.core.domain.AjaxResult;
import com.hanthink.common.core.domain.entity.SysDept;
import com.hanthink.common.core.domain.model.LoginUser;
import com.hanthink.common.exception.CustomException;
import com.hanthink.common.utils.DateUtils;
import com.hanthink.common.utils.SerialNumberUtil;
import com.hanthink.system.domain.SysSerialNumber;
import com.hanthink.system.domain.pc.EmEquip;
import com.hanthink.system.domain.repair.EquipRepairMessageVo;
import com.hanthink.system.domain.repair.RepairHelpUser;
import com.hanthink.system.domain.repair.RepairRecordInfo;
import com.hanthink.system.domain.repair.RequestInfo;
import com.hanthink.system.mapper.EmEquipMapper;
import com.hanthink.system.mapper.SysDeptMapper;
import com.hanthink.system.mapper.SysSerialNumberMapper;
import com.hanthink.system.mapper.repair.EquipRepairMapper;
import com.hanthink.system.mapper.repair.RepairHelpUserMapper;
import com.hanthink.system.mapper.repair.RepairRecoedMapper;
import com.hanthink.system.mapper.repair.RequestMapper;
import com.hanthink.system.service.repair.IResquestInfoService;


@Service
public class RequestInfoServiceImpl implements IResquestInfoService {

    @Autowired
    private RequestMapper requestMapper;

    @Autowired
    private RepairRecoedMapper repairRecoedMapper;

    @Autowired
    private RepairHelpUserMapper repairHelpUserMapper;

    @Autowired
    private SysSerialNumberMapper sysSerialNumberMapper;

    @Autowired
    private EquipRepairMapper equipRepairMapper;

    @Autowired
    private EmEquipMapper emEquipMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatMessageServiceImpl weChatMessageService;

    @Override
    public List<RequestInfo> selectRequestinforList(Long siteKey) {

        return requestMapper.selectRequestVo(siteKey);
    }

    @Override
    public List<RequestInfo> selectRequestinforListPlus(Map<String, Object> params) {

        return requestMapper.selectRequestVoPlus(params);
    }


    @Override
    public List<RequestInfo> selectRequestinforListnotget(Map<String, Object> params) {

        return requestMapper.selectRequestinforListnotget(params);
    }


    @Override
    public List<RequestInfo> selectRequestinforListget(Map<String, Object> params) {

        return requestMapper.selectRequestinforListget(params);
    }


    @Override
    public List<RequestInfo> selectRequestinforListallocation(Map<String, Object> params) {

        return requestMapper.selectRequestinforListallocation(params);
    }


    @Override
    public List<RequestInfo> checkedListzhengyi1(String siteKey) {

        return requestMapper.checkedListzhengyi1(siteKey);
    }

    @Override
    public int checkedListzhengyi3(Long siteKey) {

        return requestMapper.checkedListzhengyi3(siteKey);
    }


    @Override
    public int checkedListzhengyi31(Long siteKey) {

        return requestMapper.checkedListzhengyi31(siteKey);
    }


    @Override
    public List<RequestInfo> checkedListzhengyi50(Long siteKey) {

        return requestMapper.checkedListzhengyi50(siteKey);
    }


    @Override
    public List<RequestInfo> checkedListzhengyi51(Long siteKey) {

        return requestMapper.checkedListzhengyi51(siteKey);
    }


    @Override
    public int checkedListzhengyi32(Long siteKey) {

        return requestMapper.checkedListzhengyi32(siteKey);
    }

    @Override
    public List<RequestInfo> checkedListzhengyi10(Map<String, Object> map) {

        return requestMapper.checkedListzhengyi10(map);
    }


    @Override
    public List<RequestInfo> checkedListzhengyi15(Map<String, Object> map) {

        return requestMapper.checkedListzhengyi15(map);
    }

    @Override
    public int checkedListzhengyi7(Map<String, Object> map) {

        return requestMapper.checkedListzhengyi7(map);
    }


    @Override
    public int checkedListzhengyi6(Map<String, Object> map) {

        return requestMapper.checkedListzhengyi6(map);
    }


    @Override
    public int checkedListzhengyi88(Map<String, Object> map) {

        return requestMapper.checkedListzhengyi88(map);
    }


    @Override
    public int checkedListzhengyi61(Map<String, Object> map) {

        return requestMapper.checkedListzhengyi61(map);
    }


    @Override
    public int checkedListzhengyi62(Map<String, Object> map) {

        return requestMapper.checkedListzhengyi62(map);
    }

    @Override
    public List<RequestInfo> checkedListzhengyi2(String siteKey) {

        return requestMapper.checkedListzhengyi2(siteKey);
    }


    @Override
    public List<RequestInfo> checkedListzhengyi4(Long siteKey) {

        return requestMapper.checkedListzhengyi4(siteKey);
    }


    @Override
    public List<RequestInfo> checkedListzhengyi99(Map<String, Object> map) {

        return requestMapper.checkedListzhengyi99(map);
    }

    @Override
    public List<RequestInfo> checkedListzhengyi5(Long siteKey) {

        return requestMapper.checkedListzhengyi5(siteKey);
    }

    @Override
    public List<RequestInfo> selectRequestinforListbx(Long siteKey) {

        return requestMapper.selectRequestVobx(siteKey);
    }


    @Override
    public List<RequestInfo> selectRequestinforListbxbyCode(Map<String, Object> params) {

        return requestMapper.selectRequestVobxbyCode(params);
    }

    @Override
    public int updateassign(Map<String, Object> params) {
        // 部门指派
        int result = requestMapper.updateassign(params);
        // 成功后推送消息
        if (result > 0) {
            List<String> pushList = Collections.singletonList(String.valueOf(params.get("roleName")));
            RequestInfo requestInfo = requestMapper.selectRequestVoById(Long.parseLong(params.get("id").toString()));
            EmEquip eq = emEquipMapper.selectEmEquipByCode(requestInfo.getEquipName());
            String pushMessage = "隐患编号:" + "【" + requestInfo.getRequestCode() + "】\n设备名称：" + eq.getDesc() + "重大隐患或隐患已分配，请确认。";
            weChatMessageService.sendMessage(requestInfo.getSiteKey(), pushMessage, pushList, null);
        }
        return result;
    }

    public static void sendWeChatMessageToUser(String msg, String user) {
        try {
            if (StringUtil.isEmpty(msg)) {
                return;
            }
            String yinhuanpaicha = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c3b95aaf-5808-4d15-867c-bcbe08d4123b";
            String TEXT = "text";
            // 封装发送消息请求JSON
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("{");
            stringBuffer.append("\"msgtype\":" + "\"" + TEXT + "\",");
            stringBuffer.append("\"text\":" + "{");
            stringBuffer.append("\"content\":" + "\"" + msg + "\"");
            stringBuffer.append(",\"mentioned_list\":" + "[\"" + user + "\"]");
            stringBuffer.append("}");
            stringBuffer.append("}");
            String json = stringBuffer.toString();

            URL postUrl = new URL(yinhuanpaicha);
            HttpURLConnection http = (HttpURLConnection) postUrl.openConnection();
            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            http.setDoOutput(true);
            http.setDoInput(true);
            // 连接超时30秒
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
            // 读取超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000");
            http.connect();
            // 写入内容
            OutputStream outputStream = http.getOutputStream();
            outputStream.write(json.getBytes(StandardCharsets.UTF_8));
            InputStream inputStream = http.getInputStream();
            int size = inputStream.available();
            byte[] jsonBytes = new byte[size];
            inputStream.read(jsonBytes);
            String result = new String(jsonBytes, StandardCharsets.UTF_8);
            System.out.println("请求返回结果:" + result);

            // 清空输出流
            outputStream.flush();
            // 关闭输出通道
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor = CustomException.class)
    public int updateRequest(Map<String, Object> map) {

        try {
            // 更新整改单审核人相关信息
            if (map.get("ids") == null || "".equals(map.get("ids"))) {

                throw new CustomException(String.format("请选择待指派的数据"));
            }

            @SuppressWarnings("unchecked")
            List<String> idList = (List<String>) map.get("ids");
            Long[] ids = null;
            @SuppressWarnings("unchecked")
            List<String> equips = (List<String>) map.get("equipKey");
            List<String[]> dataList = new ArrayList<String[]>();
            for (int i = 0; i < idList.size(); i++) {
                String[] data = new String[2];
                data[0] = String.valueOf(idList.get(i));
                data[1] = String.valueOf(equips.get(i));
                dataList.add(data);
            }
            Map<String, Object> requestUsers = new HashMap<String, Object>();
            List<String[]> newDataList = new ArrayList<String[]>();
            for (int i = 0; i < dataList.size(); i++) {
                Long id = Long.valueOf(String.valueOf(dataList.get(i)[0]));
                // 校验整改单是否已指派
                RequestInfo requestInfo = requestMapper.selectRequestVoById(id);
                requestUsers.put(String.valueOf(requestInfo.getId()), requestInfo.getRequestUser());
                if (requestInfo.getCheckUser() == null) {
                    newDataList.add(dataList.get(i));
                }
            }
            if (newDataList.size() == 0) {
                return 0;
            }
            ids = new Long[newDataList.size()];
            equips = new ArrayList<String>();
            for (int i = 0; i < newDataList.size(); i++) {
                ids[i] = Long.valueOf(newDataList.get(i)[0]);
                equips.add(newDataList.get(i)[1]);

            }
            // 操作用户
            if (map.get("userName") == null || "".equals(map.get("userName"))) {

                throw new CustomException(String.format("未获取到当前登录用户信息"));
            }
            String operaUser = (String) map.get("userName");
            String userNick = (String) map.get("userNick");
            String mergetype = (String) map.get("mergetype");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("userName", operaUser);
            params.put("ids", ids);
            params.put("mergetype", mergetype);
            requestMapper.updateRequest(params);
            // 指派人
            @SuppressWarnings("unchecked")
            List<String> assignUsers = (List<String>) map.get("assignUser");
            if (equips != null && equips.size() > 0) {
                // 工厂Key
                Long siteKey = 0l;
                Integer site = (Integer) map.get("siteKey");
                if (site != null)
                    siteKey = new Long((long) site);
                // 增加维修记录信息
                List<RepairRecordInfo> list = new ArrayList<RepairRecordInfo>();
                for (int i = 0; i < equips.size(); i++) {
                    RepairRecordInfo repairRecord = new RepairRecordInfo();
                    repairRecord.setSiteKey(siteKey); // 工厂KEY
                    repairRecord.setRequestId(ids[i]);// 整改单ID
                    // 生成维修单号
                    // 获取序列号
                    SysSerialNumber serial = sysSerialNumberMapper.selectNextValue();
                    String repairCode = SerialNumberUtil.getSerialNumber(BusinessConstants.REPAIR_FLAG,
                            serial.getNextValue(), serial.getToday());
                    repairRecord.setRepairCode(repairCode); // 维修单号
                    repairRecord.setEqKey(Long.valueOf(String.valueOf(equips.get(i))));// 设备KEY
                    repairRecord.setRepairUser(assignUsers.get(0)); // 执行人
                    repairRecord.setType(BusinessConstants.REPAIR_TYPE_REQUEST); // 维修类型
                    repairRecord.setStatus(BusinessConstants.REPAIR_STATUS_WAIT); // 维修状态 -待维修
                    list.add(repairRecord);
                }
                repairRecoedMapper.insertPairRecord(list);

                // 获取新增的维修记录信息
                List<RepairRecordInfo> recordInfos = repairRecoedMapper.SelectRecordByRequestKey(params);
                // 当指派人超过1位，添加维修协助人数据
                if (assignUsers != null && assignUsers.size() > 1) {
                    List<RepairHelpUser> helpUsers = new ArrayList<RepairHelpUser>();
                    for (int i = 0; i < recordInfos.size(); i++) {
                        for (int j = 1; j < assignUsers.size(); j++) {
                            RepairHelpUser helpUser = new RepairHelpUser();
                            helpUser.setSiteKey(siteKey); // 工厂Key
                            helpUser.setRecordId(recordInfos.get(i).getId()); // 维修记录ID
                            helpUser.setUserCode(assignUsers.get(j));// 协助人编码

                            helpUsers.add(helpUser);
                        }
                    }
                    repairHelpUserMapper.insertHelpUser(helpUsers);
                }
                if (recordInfos.size() > 0) {
                    for (int i = 0; i < recordInfos.size(); i++) {
                        // 插入消息通知记录
                        EquipRepairMessageVo equipRepairMessageVo = new EquipRepairMessageVo();
                        equipRepairMessageVo.setIsPush(BusinessConstants.IS_PUSH_TRUE);
                        equipRepairMessageVo.setIsRead(BusinessConstants.IS_READ_FALSE);
                        equipRepairMessageVo.setNewsType("整改指派");
                        equipRepairMessageVo.setSendUser(
                                requestUsers.get(String.valueOf(recordInfos.get(i).getRequestId())).toString());
                        equipRepairMessageVo.setRelationId(recordInfos.get(i).getRequestId());
                        equipRepairMessageVo.setSiteKey(siteKey);

                        equipRepairMessageVo.setEqKey(recordInfos.get(i).getEqKey());
                        equipRepairMessageVo.setNotingUser(recordInfos.get(i).getRepairUser());
                        // 根据设备id查询设备信息
                        EmEquip emEquip = emEquipMapper.selectEmEquipById(recordInfos.get(i).getEqKey());
                        equipRepairMessageVo.setNewsDesc("【整改指派】\n" + emEquip.getDesc() + "[" + emEquip.getName()
                                + "]\n单号：" + recordInfos.get(i).getRepairCode() + "\n审核时间："
                                + recordInfos.get(i).getCheckTime() + "\n审核人：" + userNick + "\n请及时维修");

                        equipRepairMapper.saveEquipRepairMessageInfo(equipRepairMessageVo);
                    }
                }

            }

        } catch (Exception e) {
            throw new CustomException(String.format(e.toString()));
        }

        return 0;

    }

    /**
     * 查询已指派的整改单信息
     */
    @Override
    public List<RequestInfo> selectCheckedList(Long siteKey) {

        return requestMapper.selectCheckedList(siteKey);
    }

    @Override
    public List<RequestInfo> selectCheckedListOverTime() {

        return requestMapper.selectCheckedListOverTime();
    }


    @Override
    public void updateCheckedListOverTime(Long id) {
        requestMapper.updateCheckedListOverTime(id);
    }


    /**
     * 新增插入整改单信息
     */
    @Override
    public int insertRequest(RequestInfo requestInfo) {
        requestMapper.insertRequest(requestInfo);
        return 0;
    }

    /**
     * 整改单接单
     *
     * @param map 保修单map
     */
    @Override
    @Transactional(rollbackFor = CustomException.class)
    public int orderRequest(Map<String, Object> map) {

        try {
            // 更新整改单审核人相关信息
            if (map.get("ids") == null || "".equals(map.get("ids"))) {

                throw new CustomException(String.format("请选择待指派的数据"));
            }

            @SuppressWarnings("unchecked")
            List<String> idList = (List<String>) map.get("ids");
            Long[] ids = null;
            @SuppressWarnings("unchecked")
            List<String> equips = (List<String>) map.get("equipKey");
            List<String[]> dataList = new ArrayList<String[]>();
            for (int i = 0; i < idList.size(); i++) {
                String[] data = new String[2];
                data[0] = String.valueOf(idList.get(i));
                data[1] = String.valueOf(equips.get(i));
                dataList.add(data);
            }
            Map<String, Object> requestUsers = new HashMap<String, Object>();
            List<String[]> newDataList = new ArrayList<String[]>();
            for (int i = 0; i < dataList.size(); i++) {
                Long id = Long.valueOf(String.valueOf(dataList.get(i)[0]));
                // 校验整改单是否已指派
                RequestInfo requestInfo = requestMapper.selectRequestVoById(id);
                requestUsers.put(String.valueOf(requestInfo.getId()), requestInfo.getRequestUser());
                if (requestInfo.getCheckUser() == null) {
                    newDataList.add(dataList.get(i));
                } else {
                    throw new CustomException("整改单[" + requestInfo.getRequestCode() + "],已指派过或有人已接单，请刷新页面后重试");
                }
            }
            if (newDataList.size() == 0) {
                return 0;
            }
            ids = new Long[newDataList.size()];
            equips = new ArrayList<String>();
            for (int i = 0; i < newDataList.size(); i++) {
                ids[i] = Long.valueOf(newDataList.get(i)[0]);
                equips.add(newDataList.get(i)[1]);

            }
            // 操作用户
            if (map.get("userName") == null || "".equals(map.get("userName"))) {

                throw new CustomException(String.format("未获取到当前登录用户信息"));
            }
            String operaUser = (String) map.get("userName");
            String userNick = (String) map.get("userNick");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("userName", operaUser);
            params.put("ids", ids);
            requestMapper.updateRequest(params);

            // 指派人
            @SuppressWarnings("unchecked")
            List<String> assignUsers = (List<String>) map.get("assignUser");

            if (equips != null && equips.size() > 0) {
                // 工厂Key
                Long siteKey = 0l;
                Integer site = (Integer) map.get("siteKey");
                if (site != null)
                    siteKey = (long) site;
                // 增加维修记录信息
                List<RepairRecordInfo> list = new ArrayList<RepairRecordInfo>();
                for (int i = 0; i < equips.size(); i++) {
                    RepairRecordInfo repairRecord = new RepairRecordInfo();
                    repairRecord.setSiteKey(siteKey); // 工厂KEY
                    repairRecord.setRequestId(ids[i]);// 整改单ID
                    // 生成维修单号
                    // 获取序列号
                    SysSerialNumber serial = sysSerialNumberMapper.selectNextValue();
                    String repairCode = SerialNumberUtil.getSerialNumber(BusinessConstants.REPAIR_FLAG,
                            serial.getNextValue(), serial.getToday());
                    repairRecord.setRepairCode(repairCode); // 维修单号
                    repairRecord.setEqKey(Long.valueOf(String.valueOf(equips.get(i))));// 设备KEY
                    repairRecord.setRepairUser(assignUsers.get(0)); // 执行人
                    repairRecord.setType(BusinessConstants.REPAIR_TYPE_REQUEST); // 维修类型
                    repairRecord.setStatus(BusinessConstants.REPAIR_STATUS_WAIT); // 维修状态 -待维修
                    list.add(repairRecord);
                }

                repairRecoedMapper.insertPairRecord(list);

                // 获取新增的维修记录信息
                List<RepairRecordInfo> recordInfos = repairRecoedMapper.SelectRecordByRequestKey(params);
                // 当指派人超过1位，添加维修协助人数据
                if (assignUsers != null && assignUsers.size() > 1) {
                    List<RepairHelpUser> helpUsers = new ArrayList<RepairHelpUser>();
                    for (int i = 0; i < recordInfos.size(); i++) {
                        for (int j = 1; j < assignUsers.size(); j++) {
                            RepairHelpUser helpUser = new RepairHelpUser();
                            helpUser.setSiteKey(siteKey); // 工厂Key
                            helpUser.setRecordId(recordInfos.get(i).getId()); // 维修记录ID
                            helpUser.setUserCode(assignUsers.get(j));// 协助人编码

                            helpUsers.add(helpUser);
                        }
                    }
                    repairHelpUserMapper.insertHelpUser(helpUsers);
                }
                if (recordInfos.size() > 0) {
                    for (int i = 0; i < recordInfos.size(); i++) {
                        // 插入消息通知记录
                        EquipRepairMessageVo equipRepairMessageVo = new EquipRepairMessageVo();
                        equipRepairMessageVo.setIsPush(BusinessConstants.IS_PUSH_TRUE);
                        equipRepairMessageVo.setIsRead(BusinessConstants.IS_READ_FALSE);
                        equipRepairMessageVo.setNewsType("整改接单");
                        equipRepairMessageVo.setSendUser(
                                requestUsers.get(String.valueOf(recordInfos.get(i).getRequestId())).toString());
                        equipRepairMessageVo.setRelationId(recordInfos.get(i).getRequestId());
                        equipRepairMessageVo.setSiteKey(siteKey);
                        equipRepairMessageVo.setEqKey(recordInfos.get(i).getEqKey());
                        equipRepairMessageVo.setNotingUser("@all");
                        // 根据设备id查询设备信息
                        EmEquip emEquip = emEquipMapper.selectEmEquipById(recordInfos.get(i).getEqKey());
                        equipRepairMessageVo.setNewsDesc("【整改接单】\n" + emEquip.getDesc() + "[" + emEquip.getName()
                                + "]\n单号：" + recordInfos.get(i).getRepairCode() + "\n接单时间："
                                + recordInfos.get(i).getCheckTime() + "\n接单人：" + userNick);

                        equipRepairMapper.saveEquipRepairMessageInfo(equipRepairMessageVo);
                    }
                }

            }

        } catch (Exception e) {
            throw new CustomException(String.format(e.getMessage()));
        }

        return 0;
    }

    @Override
    @Transactional(rollbackFor = CustomException.class)
    public int orderRequestplusfirst(Map<String, Object> map) {
        try {
            // 参数校验
            if (map.get("ids") == null || "".equals(map.get("ids"))) {
                throw new CustomException("请选择待指派的数据");
            }

            String operaUser = (String) map.get("userName");
            if (operaUser == null || "".equals(operaUser)) {
                throw new CustomException("未获取到当前登录用户信息");
            }

            // 参数提取
            List<String> idList = (List<String>) map.get("ids");
            List<String> mergetypes = (List<String>) map.get("mergetype");
            List<String> firstlevelreview = (List<String>) map.get("firstlevelreview");
            String reviewType = String.valueOf(map.get("reviewType"));

            int successCount = 0;

            // 遍历处理每个整改单
            for (int i = 0; i < idList.size(); i++) {
                Long id = Long.valueOf(String.valueOf(idList.get(i)));
                // 校验整改单
                RequestInfo requestInfo = requestMapper.selectRequestVoById(id);
                // 更新整改单信息
                Map<String, Object> params = new HashMap<>();
                params.put("userName", operaUser);
                params.put("id", id);
                params.put("mergetype", mergetypes.get(i));
                params.put("firstlevelreview", firstlevelreview.get(i));

                int result = requestMapper.updateRequestByID(params);
                if (result > 0) {
                    EmEquip eq = emEquipMapper.selectEmEquipByCode(requestInfo.getEquipName());
                    successCount++;
                    // 分管领导审核
                    if ("firstLevelReview".equals(reviewType)) {
                        // 推送消息 -两片杭州隐患-安全环保部 非重大隐患
                        if (HiddenDangerType.NOT_MAJOR_HIDDEN_DANGER.getValue().equals(mergetypes.get(i))) {
                            String pushMessage = "隐患编号:" + "【" + requestInfo.getRequestCode() + "】\n设备名称：" + eq.getDesc() + "及联动系统重大隐患不成立，为非重大隐患，请组织整改。";
                            weChatMessageService.sendMessage(requestInfo.getSiteKey(), pushMessage, PushType.PUSH_TYPE_ONE.getValue(), null);
                            // 安全分管判定 -重大隐患
                        } else if (HiddenDangerType.MAJOR_HIDDEN_DANGER.getValue().equals(mergetypes.get(i))) {
                            String pushMessage = "隐患编号:" + "【" + requestInfo.getRequestCode() + "】\n设备名称：" + eq.getDesc() + "及联动系统重大隐患已审核，请批示。";
                            weChatMessageService.sendMessage(requestInfo.getSiteKey(), pushMessage, PushType.PUSH_TYPE_FOUR.getValue(), null);
                        }
                        // 主要负责人审核
                    } else if ("secondLevelReview".equals(reviewType)) {
                        // 推送消息-主要负责人审核判定 非重大隐患
                        if (HiddenDangerType.NOT_MAJOR_HIDDEN_DANGER.getValue().equals(mergetypes.get(i))) {
                            String pushMessage = "隐患编号:" + "【" + requestInfo.getRequestCode() + "】\n设备名称：" + eq.getDesc() + "及联动系统重大隐患不成立，为非重大隐患，请组织整改。";
                            weChatMessageService.sendMessage(requestInfo.getSiteKey(), pushMessage, PushType.PUSH_TYPE_TWO.getValue(), null);
                            // 主要负责人审核判定 -重大隐患
                        } else if (HiddenDangerType.MAJOR_HIDDEN_DANGER.getValue().equals(mergetypes.get(i))) {
                            String pushMessage = "隐患编号:" + "【" + requestInfo.getRequestCode() + "】\n设备名称：" + eq.getDesc() + "及联动系统重大隐患已批准，请组织整改。";
                            weChatMessageService.sendMessage(requestInfo.getSiteKey(), pushMessage, PushType.PUSH_TYPE_TWO.getValue(), null);
                        }
                    }
                }
            }
            return successCount;
        } catch (Exception e) {
            throw new CustomException(e.getMessage());
        }
    }


    @Override
    @Transactional(rollbackFor = CustomException.class)
    public int orderRequestget(Map<String, Object> map) {
        try {
            // 参数提取和验证
            List<Integer> idList = (List<Integer>) map.get("ids");
            List<Integer> equips = (List<Integer>) map.get("equipKey");
            List<String> mergetypes = (List<String>) map.get("mergetype");
            List<String> statusList = (List<String>) map.get("status");
            List<String> reasonList = (List<String>) map.get("reason");
            List<String> assignUsers = (List<String>) map.get("assignUser");

            // 验证必需参数
            String operaUser = (String) map.get("userName");
            if (operaUser == null || operaUser.trim().isEmpty()) {
                throw new CustomException("未获取到当前登录用户信息");
            }

            // 处理数据：分离需要删除和需要处理的数据
            List<Long> processIds = new ArrayList<>();
            List<String> processEquips = new ArrayList<>();
            List<String> processMergetypes = new ArrayList<>();

            for (int i = 0; i < idList.size(); i++) {
                Long id = idList.get(i).longValue();
                if ("0".equals(statusList.get(i))) {
                    // 状态为0的处理：删除部门并更新原因
                    Map<String, Object> params = new HashMap<>();
                    params.put("id", id);
                    params.put("reason", reasonList.get(i));
                    requestMapper.updateRequestByIDdeletedept(params);
                    RequestInfo requestInfo = requestMapper.selectRequestVoById(id);
                    EmEquip eq = emEquipMapper.selectEmEquipByCode(requestInfo.getEquipName());
                    // 消息推送 部门负责人判定为“非”本部门隐患
                    String pushMessage = "隐患编号:" + "【" + requestInfo.getRequestCode() + "】\n设备名称：" + eq.getDesc() + "及联动系统重大隐患或隐患非主控部门，请重新分配。";
                    weChatMessageService.sendMessage(requestInfo.getSiteKey(), pushMessage, PushType.PUSH_TYPE_ONE.getValue(), null);
                } else {
                    // 状态非0的处理：收集需要进一步处理的数据
                    processIds.add(id);
                    processEquips.add(String.valueOf(equips.get(i)));
                    processMergetypes.add(mergetypes.get(i));
                }
            }
            // 如果没有需要处理的数据，直接返回
            if (processIds.isEmpty()) {
                return 0;
            }

            // 批量更新请求信息
            Map<String, Object> updateParams = new HashMap<>();
            updateParams.put("userName", operaUser);
            updateParams.put("ids", processIds.toArray(new Long[0]));

            for (int i = 0; i < processIds.size(); i++) {
                updateParams.put("id", processIds.get(i));
                updateParams.put("mergetype", processMergetypes.get(i));
                requestMapper.updateRequestByID(updateParams);
            }

            // 处理维修记录
            if (!processEquips.isEmpty()) {
                // 工厂Key处理
                Long siteKey = 0L;
                Integer site = (Integer) map.get("siteKey");
                if (site != null) {
                    siteKey = site.longValue();
                }

                // 批量生成维修记录
                List<RepairRecordInfo> repairRecords = new ArrayList<>();
                String assignUser = assignUsers.get(0); // 获取第一个指派人

                for (int i = 0; i < processIds.size(); i++) {
                    RepairRecordInfo repairRecord = createRepairRecord(
                            processIds.get(i), processEquips.get(i), processMergetypes.get(i),
                            siteKey, assignUser
                    );
                    repairRecords.add(repairRecord);
                    RequestInfo requestInfo = requestMapper.selectRequestVoById(processIds.get(i));
                    EmEquip eq = emEquipMapper.selectEmEquipByCode(requestInfo.getEquipName());
                    // 判断是否为重大隐患
                    if (HiddenDangerType.MAJOR_HIDDEN_DANGER.getValue().equals(requestInfo.getMergetype())) {
                        // 消息推送 部门负责人判定为本部门隐患
                        String pushMessage = "隐患编号:" + "【" + requestInfo.getRequestCode() + "】\n设备名称：" + eq.getDesc() + "及联动系统重大隐患已确认，将按期组织整改。";
                        weChatMessageService.sendMessage(requestInfo.getSiteKey(), pushMessage, PushType.PUSH_TYPE_FIVE.getValue(), null);
                    } else {
                        // 消息推送 部门负责人判定为本部门隐患
                        String pushMessage = "隐患编号:" + "【" + requestInfo.getRequestCode() + "】\n设备名称：" + eq.getDesc() + "及联动系统隐患已确认，将按期组织整改。";
                        weChatMessageService.sendMessage(requestInfo.getSiteKey(), pushMessage, PushType.PUSH_TYPE_ONE.getValue(), null);
                    }
                }
                repairRecoedMapper.insertPairRecord(repairRecords);
            }

        } catch (Exception e) {
            throw new CustomException(String.format("操作失败: %s", e.getMessage()));
        }
        return 0;
    }

    /**
     * 创建维修记录
     *
     * @param requestId
     * @param equip
     * @param mergetype
     * @param siteKey
     * @param assignUser
     * @return
     */
    private RepairRecordInfo createRepairRecord(Long requestId, String equip, String mergetype,
                                                Long siteKey, String assignUser) {
        RepairRecordInfo repairRecord = new RepairRecordInfo();

        // 生成维修单号
        SysSerialNumber serial = sysSerialNumberMapper.selectNextValue();
        String repairCode = SerialNumberUtil.getSerialNumber(BusinessConstants.REPAIR_FLAG,
                serial.getNextValue(), serial.getToday());

        repairRecord.setSiteKey(siteKey);
        repairRecord.setRequestId(requestId);
        repairRecord.setRepairCode(repairCode);
        repairRecord.setEqKey(Long.valueOf(equip));
        repairRecord.setRepairUser(assignUser);
        repairRecord.setType(BusinessConstants.REPAIR_TYPE_REQUEST);
        repairRecord.setStatus(BusinessConstants.REPAIR_STATUS_WAIT);
        repairRecord.setMergetype(mergetype);

        // 重大隐患特殊处理
        if ("重大隐患".equals(mergetype)) {
            boolean rushRepairStatus = surerushrepairstatus(requestId, assignUser);
            repairRecord.setRushrepairstatus(rushRepairStatus ? 1 : 0);
        }

        return repairRecord;
    }


    @Override
    @Transactional(rollbackFor = CustomException.class)
    public int orderRequestplus(Map<String, Object> map) {
        try {
            // 参数提取
            List<Integer> idList = (List<Integer>) map.get("ids");
            List<String> mergetypes = (List<String>) map.get("mergetype");
            List<String> firstlevelreview = (List<String>) map.get("firstlevelreview");
            List<String> reason = (List<String>) map.get("reason");
            // 验证用户信息
            String operaUser = (String) map.get("userName");
            if (operaUser == null || operaUser.trim().isEmpty()) {
                throw new CustomException("未获取到当前登录用户信息");
            }
            int successCount = 0;
            // 遍历处理每个整改单
            for (int i = 0; i < idList.size(); i++) {
                Long id = idList.get(i).longValue();
                // 校验整改单是否已指派
                RequestInfo requestInfo = requestMapper.selectRequestVoById(id);
                if (requestInfo.getCheckUser() != null) {
                    throw new CustomException("整改单[" + requestInfo.getRequestCode() + "]已指派过或有人已接单，请刷新页面后重试");
                }

                // 更新整改单信息
                Map<String, Object> params = new HashMap<>();
                params.put("userName", operaUser);
                params.put("id", id);
                params.put("mergetype", mergetypes.get(i));
                params.put("firstlevelreview", firstlevelreview.get(i));

                if (reason != null && i < reason.size() && reason.get(i) != null) {
                    params.put("reason", reason.get(i));
                }

                int result = requestMapper.updateRequestByID(params);
                if (result > 0) {
                    EmEquip eq = emEquipMapper.selectEmEquipByCode(requestInfo.getEquipName());
                    successCount++;
                    // 推送消息-隐患创始人
                    if ("不是隐患".equals(mergetypes.get(i))) {
                        String pushMessage = "隐患编号:" + "【" + requestInfo.getRequestCode() + "】\n设备名称：" + eq.getDesc() + "及联动系统不成立，请确认。";
                        weChatMessageService.sendMessage(requestInfo.getSiteKey(), pushMessage, PushType.PUSH_TYPE_SEVEN.getValue(), requestInfo.getRequestUser());
                        // 隐患安全分管审核
                    } else if ("重大隐患".equals(mergetypes.get(i))) {
                        String pushMessage = "隐患编号:" + "【" + requestInfo.getRequestCode() + "】\n设备名称：" + eq.getDesc() + "及联动系统重大隐患已生成，请审核。";
                        weChatMessageService.sendMessage(requestInfo.getSiteKey(), pushMessage, PushType.PUSH_TYPE_THREE.getValue(), null);
                    }
                }
            }
            return successCount;
        } catch (Exception e) {
            if (e instanceof CustomException) {
                throw (CustomException) e;
            }
            throw new CustomException(String.format(e.getMessage()));
        }
    }

    //根据整改单号和维修人寰，判断是不是都是生产部或者生产组的人员
    private boolean surerushrepairstatus(Long requestid, String requestuser) {
        Integer index1 = userMapper.getUserbyrequestid(requestid);
        Integer index2 = userMapper.getUserbyidrole(requestuser);
        if (index1.equals(1) && index2.equals(1)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<RequestInfo> selectNoFinishedRequestVo(RequestInfo requestInfo) {

        return requestMapper.selectNoFinishedRequestVo(requestInfo);
    }

    @Override
    public AjaxResult orderPrompt(Long requestId, LoginUser loginUser) {
        try {
            // 查询整改单最新数据信息
            RequestInfo requestInfo = requestMapper.selectRequestVoById(requestId);
            if (requestInfo != null) {
                if (requestInfo.getLastPromptTime() != null) {
                    // 校验当前催促是否距离上次催促时间超过1分钟
                    if (DateUtils.getDatePoorMinute(new Date(), requestInfo.getLastPromptTime()) <= 1) {
                        return AjaxResult.error("距离上次催促时间[" + DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", requestInfo.getLastPromptTime()) + "]未超过1分钟，请稍后重试!");
                    }
                }
                // 判断当前催促属于第几次
                int promptTimes = requestInfo.getPromptTimes() != null ? requestInfo.getPromptTimes().intValue() : 0;
                switch (promptTimes) {
                    case 0:
                        // 重发一次整改消息
                        // 插入消息通知记录
                        sendMessage(loginUser.getUser().getUserName(), requestId, loginUser.getUser().getSite(),
                                requestInfo.getEqKey(), "@all", requestInfo.getRequestCode());
                        break;
                    case 1:
                        // 催促提醒到设备部门主管
                        if (null != loginUser.getUser().getSite()) {
                            SysDept sysDept = new SysDept();
                            sysDept.setParentId(loginUser.getUser().getSite());
                            List<SysDept> deptList = sysDeptMapper.selectDeptList(sysDept);
                            if (deptList.size() > 0) {
                                for (SysDept dept : deptList) {
                                    // 部门负责人是否为空
                                    if (dept.getLeader() != null && !"".equals(dept.getLeader())) {
                                        // 插入催促消息
                                        sendMessage(loginUser.getUser().getUserName(), requestId,
                                                loginUser.getUser().getSite(), requestInfo.getEqKey(), dept.getLeader(),
                                                requestInfo.getRequestCode());
                                    }
                                }
                            }
                        }

                        break;
                    case 2:
                        // 催促提醒到利润点负责人
                        if (null != loginUser.getUser().getSite()) {
                            SysDept sysDept = sysDeptMapper.selectDeptById(loginUser.getUser().getSite());
                            if (sysDept != null && sysDept.getLeader() != null && !"".equals(sysDept.getLeader())) {
                                // 插入催促消息
                                sendMessage(loginUser.getUser().getUserName(), requestId, loginUser.getUser().getSite(),
                                        requestInfo.getEqKey(), sysDept.getLeader(), requestInfo.getRequestCode());
                            }
                        }
                        break;

                    default:
                        // 催促提醒到利润点负责人
                        if (null != loginUser.getUser().getSite()) {
                            SysDept sysDept = sysDeptMapper.selectDeptById(loginUser.getUser().getSite());
                            if (sysDept != null && sysDept.getLeader() != null && !"".equals(sysDept.getLeader())) {
                                // 插入催促消息
                                sendMessage(loginUser.getUser().getUserName(), requestId, loginUser.getUser().getSite(),
                                        requestInfo.getEqKey(), sysDept.getLeader(), requestInfo.getRequestCode());
                            }
                        }
                        break;
                }

                // 更新整改单
                requestInfo.setPromptTimes(Long.valueOf(promptTimes + 1));
                requestMapper.updateRequestPrompt(requestInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("整改单催促异常，请联系管理员!");
        }

        return AjaxResult.success();
    }

    public void sendMessage(String sendUser, Long relationId, Long siteKey, Long eqKey, String notingUser,
                            String orderCode) {
        EquipRepairMessageVo equipRepairMessageVo = new EquipRepairMessageVo();
        equipRepairMessageVo.setIsPush(BusinessConstants.IS_PUSH_TRUE);
        equipRepairMessageVo.setIsRead(BusinessConstants.IS_READ_FALSE);
        equipRepairMessageVo.setNewsType("设备整改");
        equipRepairMessageVo.setSendUser(sendUser);
        equipRepairMessageVo.setRelationId(relationId);
        equipRepairMessageVo.setSiteKey(siteKey);
        equipRepairMessageVo.setEqKey(eqKey);
        equipRepairMessageVo.setNotingUser(notingUser);
        // 根据设备id查询设备信息
        EmEquip emEquip = emEquipMapper.selectEmEquipById(eqKey);
        equipRepairMessageVo.setNewsDesc("【整改催促】\n" + emEquip.getDesc() + "[" + emEquip.getName() + "]\n单号：" + orderCode
                + "\n催促时间：" + DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss") + "\n请尽快处理");
        equipRepairMapper.saveEquipRepairMessageInfo(equipRepairMessageVo);
    }

    public String selectRequestVoByName(String equipName) {

        return requestMapper.selectRequestVoByName(equipName);
    }
}
